package cn.francis.common.core.model;


import cn.francis.common.enums.CommonErrorCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import java.io.Serial;
import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @author admin
 */
@Data
@NoArgsConstructor
@Schema(description = "请求响应对象")
@ToString
public class AppResponse<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    @Schema(description = "消息状态码")
    private String code;

    @Schema(description = "消息内容")
    private String message;

    @Schema(description = "数据对象")
    private T data;

    public static <T> AppResponse<T> ok() {
        return restResult(null, CommonErrorCode.SUCCESS.getCode(), CommonErrorCode.SUCCESS.getMessage());
    }

    public static <T> AppResponse<T> ok(T data) {
        return restResult(data, CommonErrorCode.SUCCESS.getCode(), CommonErrorCode.SUCCESS.getMessage());
    }

    public static <T> AppResponse<T> ok(String msg, T data) {
        return restResult(data, CommonErrorCode.SUCCESS.getCode(), msg);
    }

    public static <T> AppResponse<T> fail() {
        return restResult(null, CommonErrorCode.SUCCESS.getCode(), CommonErrorCode.SYSTEM_ERROR.getMessage());
    }

    public static <T> AppResponse<T> fail(String msg) {
        return restResult(null, CommonErrorCode.SYSTEM_ERROR.getCode(), msg);
    }

    public static <T> AppResponse<T> fail(T data) {
        return restResult(data, CommonErrorCode.SYSTEM_ERROR.getCode(), CommonErrorCode.SYSTEM_ERROR.getMessage());
    }

    public static <T> AppResponse<T> fail(String msg, T data) {
        return restResult(data, CommonErrorCode.SYSTEM_ERROR.getCode(), msg);
    }

    public static <T> AppResponse<T> fail(String code, String msg) {
        return restResult(null, code, msg);
    }
    public static <T> AppResponse<T> fail(T date,String code, String msg) {
        return restResult(date, code, msg);
    }

    private static <T> AppResponse<T> restResult(T data, String code, String msg) {
        AppResponse<T> r = new AppResponse<>();
        r.setCode(code);
        r.setData(data);
        r.setMessage(msg);
        return r;
    }

    @Schema(description = "是否成功")
    public boolean isOk() {
        return StringUtils.equalsAnyIgnoreCase(code, CommonErrorCode.SUCCESS.getCode());
    }

}
